<template>
    <div>
      <div class="login">
        <div class="cover">
          <h1 class="title">Free Chat 注册</h1>
          <div class="input">
            <el-form :model="ruleForm" :rules="rules" ref="ruleForm">
              <el-form-item>
                <div style="display: flex;justify-content: space-around">
                  <div style="position: relative;width: 80px;height: 80px;border-radius: 50%" @mouseover="showDelete" @mouseout="hideDelete">
                    <!--头像-->
                    <img v-if="ruleForm.avatar.length !== 0" :src="ruleForm.avatar" width="80px" height="80px" style="border-radius: 10px;">
                    <!--上传头像-->
                    <div v-if="ruleForm.avatar.length === 0" title="上传头像" @click="showClipPicture" class="el-icon-user-solid" style="width: 80px;height: 80px;border-radius: 10px;
                    background-color: #909399;color: white;font-size: 50px;text-align: center;line-height: 80px;display: flex;justify-content: space-around;cursor: pointer"></div>
                    <!--删除头像-->
                    <div v-if="ruleForm.avatar.length !== 0" v-show="deleteVisible" style="display:flex;justify-content: space-around;align-items: center;border-radius: 10px;
    position: absolute;top: 0; left: 0;right: 0;bottom: 0;z-index: 10;background-color: rgba(0,0,0,.5)">
                      <i class="el-icon-delete" style="color: white;cursor: pointer;" @click="deleteAvatar"></i>
                    </div>
                  </div>
                </div>
              </el-form-item>
              <el-form-item prop="username">
                <el-input class="input-item" v-model="ruleForm.username" placeholder="用户名">
                  <template slot="prepend"><i class="el-icon-user" style="font-size: 25px"></i></template>
                </el-input>
              </el-form-item>
              <el-form-item prop="nickname">
                <el-input class="input-item" v-model="ruleForm.nickname" placeholder="昵称">
                  <template slot="prepend"><i class="el-icon-s-custom" style="font-size: 25px"></i></template>
                </el-input>
              </el-form-item>
              <el-form-item prop="password">
                <el-input  class="input-item" v-model="ruleForm.password" placeholder="密码" show-password>
                  <template slot="prepend"><i class="el-icon-lock" style="font-size: 25px"></i></template>
                </el-input>
              </el-form-item>
              <el-form-item prop="gender">
                <div class="input-item" style="border-radius: 4px;width: calc(100% - 2px);height: 40px;padding: 0;border: 1px solid #DCDFE6">
                  <div style="display: inline-block;width: 65px;height: 40px;text-align: center;margin-right: 10px;
                  border-right: 1px solid #DCDFE6;background-color: #F5F7FA;">
                    <i class="iconfont icon-gender" style="font-size: 25px;color: #909399"></i>
                  </div>
                  <el-radio v-model="ruleForm.gender" :label="0">
                    <span>男</span>
                  </el-radio>
                  <el-radio v-model="ruleForm.gender" :label="1">
                    <span>女</span>
                  </el-radio>
                </div>
              </el-form-item>
              <el-form-item prop="gender">
                <div class="input-item" style="border-radius: 4px;width: calc(100% - 2px);height: 40px;padding: 0;border: 1px solid #DCDFE6">
                  <div style="display: inline-block;width: 65px;height: 40px;text-align: center;border-right: 1px solid #DCDFE6;background-color: #F5F7FA;">
                    <i class="iconfont icon-city" style="font-size: 25px;color: #909399"></i>
                  </div>
                  <el-cascader class="cascader" v-model="ruleForm.districtId" style="position:relative;top: -4px;width: 327px" :props="props" :options="options" placeholder="请选择地区">
                  </el-cascader>
                </div>
              </el-form-item>
              <el-form-item prop="email">
                <el-input  class="input-item" v-model="ruleForm.email" placeholder="邮箱">
                  <template slot="prepend"><i class="iconfont icon-email" style="font-size: 25px"></i></template>
                  <template slot="append">
                    <el-button v-if="code.status === 0" @click="getEmailCode">获取验证码</el-button>
                    <el-button v-if="code.status === 1" disabled>
                      获取<i class="el-icon-loading"></i>
                    </el-button>
                    <el-button v-if="code.status === 2" disabled>
                      {{code.countDown}}秒后重新获取
                    </el-button>
                  </template>
                </el-input>
              </el-form-item>
              <el-form-item prop="emailCode">
                <el-input  class="input-item" v-model="ruleForm.emailCode" placeholder="验证码">
                  <template slot="prepend"><i class="iconfont icon-code" style="font-size: 25px"></i></template>
                </el-input>
              </el-form-item>
              <el-form-item>
                <el-button class="input-item" type="primary" v-if="processing" disabled>注册中...</el-button>
                <el-button class="input-item" type="primary" v-else @click="submitForm('ruleForm')">注 册</el-button>
              </el-form-item>
            </el-form>
          </div>
        </div>
      </div>
      <input ref="fileInput" type="file" accept=".jpg,.jpeg,png" style="display: none" @change="handleSelectAvatar">
      <clip-picture v-if="clipPictureVisible" @getUrl="getAvatarUrl"></clip-picture>
    </div>
</template>

<script>
import ClipPicture from '../components/ClipPicture'
export default {
  data () {
    return {
      clipPictureVisible: false,
      deleteVisible: false,
      // 角色的下拉菜单的选项数据
      roleListOptions: [],
      // 表单
      ruleForm: {
        username: '',
        password: '',
        nickname: '',
        avatar: '',
        gender: 0,
        email: '',
        districtId: [],
        emailCode: ''
      },
      // 表单验证规则
      rules: {
        username: [
          {required: true, message: '请输入用户名', trigger: 'blur'},
          { pattern: /^[a-zA-Z][a-zA-Z0-9_]{6,12}$/, message: '用户名只能包含字母、数字和下划线，且以字母开头，长度为6到12', trigger: 'blur' }
        ],
        password: [
          {required: true, message: '请输入密码', trigger: 'blur'},
          { pattern: /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d).{6,12}$/, message: '包含至少一个大写字母、一个小写字母和一个数字，长度为6到12', trigger: 'blur' }
        ],
        nickname: [
          {required: true, message: '请输入昵称', trigger: 'blur'},
          {min: 2, max: 15, message: '长度在 2 到 15 个字符', trigger: 'blur'}
        ],
        email: [
          {required: true, message: '请输入邮箱', trigger: 'blur'},
          { pattern: /^[^\s@]+@[^\s@]+\.[^\s@]+$/, message: '邮箱格式错误', trigger: 'blur' }
        ],
        emailCode: [
          {required: true, message: '请输入验证码', trigger: 'blur'}
        ],
        gender: [
          {required: true, message: '请选择性别', trigger: 'blur'}
        ]
      },
      props: {
        lazy: true,
        lazyLoad: (node, resolve) => {
          const id = node.value
          const level = node.level
          this.axios.get(`/api/v1/district/tree/${id}`).then((response) => {
            if (response.data.code === 1) {
              let children = response.data.data[0].children
              for (let i = 0; i < children.length; i++) {
                children[i].leaf = level === 1 // 设置最后一级节点为叶子节点，可选择
              }
              resolve(children)
            }
          })
        }
      },
      options: [],
      processing: false,
      code: {
        status: 0,
        countDown: 0,
        timer: null
      }
    }
  },
  methods: {
    showClipPicture () {
      if (this.clipPictureVisible === true) {
        this.clipPictureVisible = false
        setTimeout(() => {
          this.clipPictureVisible = true
        }, 500)
      } else {
        this.clipPictureVisible = true
      }
    },
    showDelete () {
      this.deleteVisible = true
    },
    hideDelete () {
      this.deleteVisible = false
    },
    getAvatarUrl (url) {
      this.ruleForm.avatar = url
      this.clipPictureVisible = false
    },
    // 选择头像
    selectAvatar () {
      // 重置value，多次选择同一文件才可触发
      this.$refs.fileInput.value = null
      this.$refs.fileInput.click()
    },
    async handleSelectAvatar (event) {
      let files = event.target.files
      this.ruleForm.avatar = await this.uploadAvatar(files[0])
    },
    // 上传头像,获取url
    async uploadAvatar (file) {
      const loading = this.$loading({
        target: '.moment-publish',
        text: '上传头像中',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })

      try {
        const formData = new FormData()
        formData.append('file', file)
        const response = await this.axios.post('/api/v1/file/upload', formData, {
          headers: {
            'Content-type': 'multipart/form-data'
          }
        })

        loading.close()

        if (response.data.code === 1) {
          let url = response.data.data
          return url
        } else {
          this.$message.error('头像上传失败!')
          return null
        }
      } catch (error) {
        loading.close()
        this.$message.info('服务器繁忙!')

        console.log('error ' + error)
      }
    },
    // 根据url删除头像
    deleteAvatar () {
      const formData = new FormData()
      formData.append('fileName', this.ruleForm.avatar)
      this.axios.post('/api/v1/file/delete', formData, {
        headers: {
          'Content-type': 'multipart/form-data'
        }
      }).then((response) => {
        if (response.data.code === 1) {
          this.$message.success('删除成功!')
          this.ruleForm.avatar = ''
        } else {
          this.$message.error('删除失败!')
          console.log('deleteFile data = ' + response.data.message)
        }
      })
    },
    // 提交表单
    submitForm (formName) {
      if (this.ruleForm.avatar.length === 0) {
        this.$alert('请上传头像', '提示', {
          confirmButtonText: '确定',
          callback: action => {
          }
        })
        return
      } else if (this.ruleForm.districtId.length !== 2) {
        this.$alert('请选择地区', '提示', {
          confirmButtonText: '确定',
          callback: action => {
          }
        })
        return
      }

      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.ruleForm.districtId = this.ruleForm.districtId[1]
          console.log('this.form = ', this.ruleForm)
          this.processing = true
          this.axios.post('/api/v1/user/register', this.ruleForm).then((response) => {
            if (response.data.code === 1) {
              this.$message.success('注册成功！')
              this.$router.push('/')
            } else {
              this.processing = false
              this.$message.error(response.data.message)
              console.error(response.data.message)
            }
          }).catch((error) => {
            this.processing = false
            this.$message.error(error)
            console.error(error)
          })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    getEmailCode () {
      let email = this.ruleForm.email
      const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
      if (emailRegex.test(email)) {
        this.code.status = 1
        this.axios.get(`/api/v1/mail/verify_code?email=${email}`).then((response) => {
          if (response.data.code === 1) {
            this.code.status = 2
            this.$message.success('验证码发送成功!')
            this.startCountDown()
          } else {
            this.code.status = 0
            this.$message.error(response.data.message)
            console.error(response.data.message)
          }
        }).catch((error) => {
          this.code.status = 0
          this.processing = false
          this.$message.error(error)
          console.error(error)
        })
      } else {
        this.$alert('邮箱格式错误!', '提示', {
          confirmButtonText: '关闭',
          type: 'info',
          callback: action => {
          }
        })
      }
    },
    startCountDown () {
      // 假设点击获取验证码后，发送验证码请求，请求成功后执行以下代码
      // 启动倒计时
      this.code.countDown = 60
      this.code.timer = setInterval(() => {
        if (this.code.countDown > 0) {
          this.code.countDown--
        } else {
          this.code.status = 0
          clearInterval(this.code.timer)
        }
      }, 1000)
    }
  },
  mounted () {
    this.axios.get(`/api/v1/district/tree/0`).then((response) => {
      if (response.data.code === 1) {
        this.options = response.data.data
      } else {
        console.error(response.data.message)
      }
    })
  },
  components: {
    ClipPicture
  }
}
</script>

<style lang="stylus" rel="stylesheet/stylus">
.cascader .el-input__inner
  border none
.el-form-item
  margin-bottom 0
.cover
  position absolute
  top 0
  bottom 0
  left 0
  width 100%
  background-color rgba(0, 0, 0, 0.51)
  z-index 2
.login
  position absolute
  top 0
  bottom 0
  left 0
  width 100%
  background-image url("../assets/background.jpg")
  background-size cover
  background-repeat no-repeat
  .title
    padding-top 80px
    padding-bottom 30px
    text-align center
    font-size 35px
    font-weight bold
    color #ffffff
  .input
    min-width 200px
    max-width 400px
    margin 20px auto
    padding 20px
    border-radius 20px
    background white
    .input-item
      width 100%
      margin-top 20px
</style>
